package ee.cafe;

import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.util.time.Duration;

public class HomePage extends WebPage {
  public HomePage() {
    final WebMarkupContainer chatMessageBox = new WebMarkupContainer("chatMessageBox");
    add(chatMessageBox.setOutputMarkupId(true));

    final PropertyListView<ChatMessage> chatMessages = new PropertyListView<ChatMessage>("chatMessages", ChatMessageList.getMessages()) {
      protected void populateItem(ListItem<ChatMessage> listItem) {
        listItem.add(new Label("timestamp") {
          
        });
        listItem.add(new Label("author"));
        listItem.add(new Label("text"));
      }
    };
    chatMessageBox.add(chatMessages);
    add(new AbstractAjaxTimerBehavior(Duration.ONE_SECOND) {
      protected void onTimer(AjaxRequestTarget target) {
        target.addComponent(chatMessageBox);
      }
    });

    Form<ChatMessageFormObject> addMessageForm = new Form<ChatMessageFormObject>("addMessageForm", new CompoundPropertyModel<ChatMessageFormObject>(new ChatMessageFormObject())) {
      @Override
      protected void onSubmit() {
        ChatMessageFormObject messageFromForm = getModelObject();
        ChatMessageList.addMessage(messageFromForm.createChatMessage());
      }
    };
    addMessageForm.add(new TextField("author"));
    addMessageForm.add(new TextField("text"));
    addMessageForm.add(new Button("addMessageButton"));
    add(addMessageForm);
  }

  private static class ChatMessageFormObject extends ChatMessage {
    public ChatMessageFormObject() {

    }

    public void setAuthor(String author) {
      this.author = author;
    }

    public void setText(String text) {
      this.text = text;
    }

    public ChatMessage createChatMessage() {
      return new ChatMessage(author, text);
    }
  }
}
